package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.entity.SetmealDto;
import com.itheima.reggie.mapper.SetMealMapper;
import com.itheima.reggie.service.SetMealDishService;
import com.itheima.reggie.service.SetMealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author :XingJiaCheng
 * @date :2022-26-20-17:26
 * @description
 **/
@Slf4j
@Service
public class SetMealServiceImpl extends ServiceImpl<SetMealMapper, Setmeal> implements SetMealService {
    @Autowired
    private SetMealDishService setMealDishService;

    @Transactional
    @Override
    public void saveWithDish(SetmealDto setmealDto) {
        log.info("stemalDto:{}", setmealDto);
        this.save(setmealDto);
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(setmealDto.getId());

        }
        setMealDishService.saveBatch(setmealDishes);
    }

    @Transactional
    @Override
    public void deleteWithIds(List<Long> ids) {
        LambdaQueryWrapper<Setmeal> QueryWrapper = new LambdaQueryWrapper<>();
        QueryWrapper.eq(Setmeal::getStatus, 1);
        QueryWrapper.in(Setmeal::getId, ids);
        int count = this.count(QueryWrapper);
        if (count > 0) {
            throw new CustomException("正在售卖,不许删除!!!!!!!!!!");
        }
        this.removeByIds(ids);
        LambdaQueryWrapper<SetmealDish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.in(SetmealDish::getSetmealId, ids);
        setMealDishService.remove(dishLambdaQueryWrapper);
    }

}
